package com.demo.controller;
 
import com.demo.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
 
/**
 * 文件上传下载
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
    private static final String NULL_FILE = "";
 
    @Value("${define.nginx.uploadPath}")
    private String uploadPath;
 
    @Autowired
    private FileService fileService;
 
    /**
     * 页面跳转接口，用于网页测试，
     * 表示：跳转到 upload.html 页面
     * 使用的是Thymeleaf 模板引擎
     * @return
     */
    @GetMapping(value = "/goToUpload")
    public String goToUploadHtml() {
        return "upload";
    }
 
 
    /**
     * 单文件上传
     * @param file
     * @return
     */
    @PostMapping("/uploadFile")
    @ResponseBody
    public String singleFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            if (file == null || NULL_FILE.equals(file.getOriginalFilename())) {
                return "upload failure";
            }
            fileService.saveFile(file.getBytes(), uploadPath, file.getOriginalFilename());
        } catch (Exception e) {
            return "upload failure";
        }
        return "upload success";
    }
 
    /**
     * 批量文件上传
     * @param files
     * @return
     */
    @PostMapping("/uploadFiles")
    @ResponseBody
    public String multiFileUpload(@RequestParam("file") MultipartFile[] files) {
        try {
 
            for (int i = 0; i < files.length; i++) {
                //check file
                if (NULL_FILE.equals(files[i].getOriginalFilename())) {
                    continue;
                }
                fileService.saveFile(files[i].getBytes(), uploadPath, files[i].getOriginalFilename());
            }
        } catch (Exception e) {
            return "upload failure";
        }
        return "upload success";
    }
 
 
    /**
     * 文件下载
     * @param response
     * @param fileName
     * @param model
     */
    @PostMapping("/download")
    public void  testDownload(HttpServletResponse response, String fileName , Model model) {
        fileService.download(response,fileName,model);
 
        //成功后返回成功信息
        model.addAttribute("result","下载成功");
    }
 
 
}
 